/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package net.huangp.dao;

import net.huangp.domain.Status;
import net.huangp.domain.Transaction;
import org.hibernate.SessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.stereotype.Repository;

/**
 *
 * @author Patrick Huang
 */
@Repository("smsTransactionDAO")
public class TransactionDAOHbnImpl implements TransactionDAO{
    //--------------------------------------------------------------------------
    // Static Properties
    //--------------------------------------------------------------------------
    private static final Logger logger = LoggerFactory.getLogger(TransactionDAOHbnImpl.class);
    public static final String QUERY_UPDATE_TRAN_STATUS
            = "update Transaction tran set tran.status = ?,tran.responseTime = current_timestamp() where tran.id = ?";
    //--------------------------------------------------------------------------
    // Properties
    //--------------------------------------------------------------------------
    private SessionFactory factory;

    private HibernateTemplate hibernateTemplate;
    // -------------------------------------------------------------------------
    // Implementation Methods
    // -------------------------------------------------------------------------
    @Autowired
    public TransactionDAOHbnImpl(SessionFactory factory){
        this.factory = factory;
        this.hibernateTemplate = new HibernateTemplate(factory);
    }

    public Transaction createTransaction(String request) {
        final Transaction tran = new Transaction(request);
        logger.info("about to save transaction:{}",tran);
        this.hibernateTemplate.save(tran);
        return tran;
    }

    public synchronized void updateTransactionStatus(Long id,Status status) {
        logger.info("about to update tran [{}] with status[{}]",
                new Object[]{id,status});
        this.hibernateTemplate.bulkUpdate(QUERY_UPDATE_TRAN_STATUS, status, id);
    }

    public Transaction getTransactionById(Long id) {
        return this.hibernateTemplate.get(Transaction.class, id);
    }
    // -------------------------------------------------------------------------
    // Mutator Methods
    // -------------------------------------------------------------------------
}
